#include "dynamicvalue.h"

DynamicValue::DynamicValue(float v)
{
    value = v;
    targeting = false;
    target = value;

    damping =  .45;//10.0;//.45;
    attraction = .2;//.9;
    mass = 1.0;

    velocity = 0.0;
    acceleration = 0.0;
    force = 0.0;

    floor = - 99999999999.0;
    ceiling = -floor;
    targetStopThreshold = 1.0;//what distance between target and value is permitted
}

//here you can set a target for the dynamic value
void DynamicValue::setTarget(float t)
{
    target = t;
    targeting = true;
}

//here you can over-ride the targeting and set a value
void DynamicValue::setValue(float v)
{
    value = v;
    targeting = false;
}

//damping and attraction alter the movement patterns
void DynamicValue::setDamping( float d )
{
    damping = d;
}

void DynamicValue::setAttraction( float a )
{
    attraction = a;
}

//floor gives minimal value permitted- so won't bounce out of bounds
void DynamicValue::setFloor( float f )
{
    floor = f;
}

void DynamicValue::setCeiling( float c )
{
    ceiling = c;
}

void DynamicValue::setTargetStopThreshold( float t )
{
    targetStopThreshold = t;
}


void DynamicValue::update()
{
    if( !targeting )//make sure not computing update, if none required
        return;
    if( abs(target - value) < targetStopThreshold )
    {
        value = target;
        targeting = false;
        return;
    }
//    if( noBounce )
//    {
//        if( posDirection && value > target )
//        {
//            value = target;
//            targeting = false;
//            return;
//        }
//        if( !posDirection && value < target )
//        {
//            value = target;
//            targeting = false;
//            return;
//        }
//    }

    force = force + attraction * (target - value );

    acceleration = force / mass ;
    velocity = (velocity + acceleration) * damping ;
    value = value + velocity;

    //constrain to bounds
    if( value < floor)
        value = floor;
    if( value > ceiling)
        value = ceiling;

    force = 0.0;
}

bool DynamicValue::isTargeting()
{
    return targeting;
}
